package com.xpqh.ai.service;

import com.openai.client.OpenAIClient;
import com.xpqh.ai.config.OpenAiConfig;
import com.xpqh.ai.dto.ChatRequest;
import com.xpqh.ai.dto.ChatResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * OpenAI服务类
 */
@Service
@Slf4j
public class OpenAiService {
    
    @Autowired
    private OpenAIClient openAIClient;
    
    @Autowired
    private OpenAiConfig openAiConfig;
    
    /**
     * 发送聊天消息
     */
    public ChatResponse chat(ChatRequest request) {
        long startTime = System.currentTimeMillis();
        
        try {
            // 确定使用的模型
            String model = StringUtils.hasText(request.getModel()) ? 
                    request.getModel() : openAiConfig.getDefaultModel();
            
            // 暂时返回模拟响应，待API调用成功后替换
            String responseContent = "这是一个模拟的ChatGPT响应。实际的API调用将在配置正确的API密钥后工作。用户输入: " + request.getMessage();
            
            ChatResponse response = ChatResponse.success(responseContent, model);
            response.setTotalTokens(100);
            response.setPromptTokens(50);
            response.setCompletionTokens(50);
            response.setRequestId("mock-request-id");
            response.setProcessingTime(System.currentTimeMillis() - startTime);
            
            log.info("ChatGPT调用成功，模型：{}，耗时：{}ms", model, response.getProcessingTime());
            
            return response;
            
        } catch (Exception e) {
            log.error("ChatGPT调用失败", e);
            ChatResponse errorResponse = ChatResponse.error("调用ChatGPT失败: " + e.getMessage());
            errorResponse.setProcessingTime(System.currentTimeMillis() - startTime);
            return errorResponse;
        }
    }
    
    /**
     * 获取可用模型列表
     */
    public List<String> getAvailableModels() {
        try {
            List<String> models = new ArrayList<>();
            models.add("gpt-4");
            models.add("gpt-4-turbo");
            models.add("gpt-3.5-turbo");
            models.add("gpt-3.5-turbo-16k");
            return models;
        } catch (Exception e) {
            log.error("获取模型列表失败", e);
            return new ArrayList<>();
        }
    }
} 